package com.aerospace.example.serialization;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * @ClassName ProtoSeri
 * @Description
 * @Author yuhang11
 * @Date 2021/12/7 7:18 下午
 * @Version 1.0
 */
@Slf4j
public class ProtoSeri {
    public static void main(String[] args) {
        byte[] pbs =protoSerialization();
        protoUnSerialization(pbs);

        javaSerialization();
    }

    private static void protoUnSerialization(byte[] pbs) {
        try {
            System.out.println("Proto反序列化的对象信息：");
            ProtoTest.SearchRequest searchRequest = ProtoTest.SearchRequest.parseFrom(pbs);
            System.out.println(searchRequest.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用proto数据格式序列化
     * @return
     */
    public static byte[] protoSerialization(){
        ProtoTest.SearchRequest searchRequest = ProtoTest.SearchRequest.newBuilder().
                setQuery("Hi,Weibo").setPageNumber(1).setResultPerPage(1).build();
        byte[] results = searchRequest.toByteArray();
        System.out.println("Proto序列化长度为"+results.length);
        System.out.print("Proto序列化后的结果为：[");
        for (byte b : results){
            System.out.print(String.valueOf(b)+",");
        }
        System.out.println("]");
        return results;
    }

    public static void javaSerialization(){
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.setQuery("Hi,Weibo");
        searchRequest.setPage_number(1);
        searchRequest.setResult_per_page(1);
        System.out.println(searchRequest.toString());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ObjectOutputStream os = new ObjectOutputStream(out);
            os.writeObject(searchRequest);
            os.flush();
            byte[] bs = out.toByteArray();
            System.out.println("jdk序列化长度为"+bs.length);
            System.out.print("jdk序列化后的结果为：[");
            for (byte b : bs){
                System.out.print(String.valueOf(b)+",");
            }
            System.out.println("]");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
